package com.cloud.code.clone;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;

import java.io.*;

/**
 * clone 是浅拷贝 ， 可以通过序列化来实现深拷贝
 */
@Data
public class User implements Serializable {

    private String username;

    private Parent parent;

    public User(String username) {
        this.username = username;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }


    @SneakyThrows
    @Override
    protected Object clone() throws CloneNotSupportedException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream outputStream = new ObjectOutputStream(byteArrayOutputStream);
        outputStream.writeObject(this);

        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        ObjectInputStream inputStream = new ObjectInputStream(byteArrayInputStream);
        User user = (User) inputStream.readObject();
        return user;
    }
}

@Data
@AllArgsConstructor
@NoArgsConstructor
class Parent implements Serializable{
    public String name;
}


class Main{
    @SneakyThrows
    public static void main(String[] args) {
        User user = new User("lxs");
        Parent parent = new Parent("lxs");
        user.setParent(parent);
        User clone = (User) user.clone();

        System.out.println(user);
        System.out.println(clone);

        clone.getParent().setName("test");

        System.out.println(user);
        System.out.println(clone);

        System.out.println(user ==  clone);


    }
}
